<?php
/**
 * Created by PhpStorm.
 * User: jingshou
 * Date: 2017/8/30
 * Time: 0:07
 */

namespace app\admin\model;

use think\Db;
use think\Model;
use think\Session;

class Config extends Model
{

    protected $table = 'tp_config';

    public function getInfo(array $condition)
    {
        return self::where($condition)->order('id asc')->limit(1)->find();
    }

    public function main(array $data)
    {
        $validate = validate('Config');
        if (!$validate->check($data)) {
            return resError($validate->getError());
        }

        if (!isset($data['id']) || empty($data['id'])) {
            return $this->configAdd($data);
        } else {
            return $this->configUpdate($data);
        }

    }

    public function configAdd(array $data)
    {
        if (empty($data)) {
            return resError('参数为空');
        }

        Db::startTrans();
        try {
            $model = new Config();
            $model->data($data);
            $model->language = Session::get('language');
            if ($model->save() == 0) {
                return resError($model->getError());
            }

            Db::commit();
            return resData('提交成功', '', $model->toArray());
        } catch (\Exception $e) {
            Db::rollback();
            return resError($e->getMessage());
        }
    }

    public function configUpdate(array $data)
    {
        $model = Config::get($data['id']);
        $model->data($data);
        if ($model->save() == 0) {
            return resError('更新失败');
        }
        return resData('更新成功', '', $model->toArray());
    }

    public function setCloseAttr()
    {
        return $this->close == 'on' ? 1 : 0;
    }
}